package com.softeem.mpdemo.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.mpdemo.dto.Result;
import com.softeem.mpdemo.entity.Admin;
import com.softeem.mpdemo.mapper.AdminMapper;
import com.softeem.mpdemo.service.AdminService;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Queue;
@Service//由Spring
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {


    @Override
    public Result login(Admin admin) {
        //先根据用户名查询是否存在
        //创建查询条件构造器(select * from where username=xxx)
        QueryWrapper<Admin> query =Wrappers.query(Admin.class);
        query.eq("username",admin.getUsername());
        //根据给定的条件构造器查询对象
        Admin a = getOne(query);
        if(Objects.isNull(a)){
            return Result.fail().setMsg("用户不存在");
        }
        if(a.getStatus() !=0){
            return Result.fail().setMsg("账号禁用").setCode(1);
        }
        //将数据库中歌用户的盐取出并与用户输入的密码组合
        String pwd = SecureUtil.md5(a.getSalt() + admin.getPassword());
        admin.setPassword(pwd);

        if(Objects.equals(a.getPassword(),admin.getPassword())){
            return Result.ok().setMsg("登陆成功").setData(a);
        }
        return Result.fail().setMsg("密码不对").setCode(2);
    }

    @Override
    public Result reg(Admin admin) {
        //添加注册(先查询)
        QueryWrapper<Admin> query =Wrappers.query(Admin.class);
        query.eq("username",admin.getUsername());

        Admin a = getOne(query);
        if(Objects.nonNull(a)){
            return Result.fail().setMsg("用户已存在");

        }
        //生成随机盐
        String salt= RandomUtil.randomString(6);
        admin.setSalt(salt);
        String pwd= salt+admin.getPassword();
//        使用md5加密
        pwd = SecureUtil.md5(pwd);
//        填充加密密码到对象中
        admin.setPassword(pwd);
        //布尔结果,执行添加并判断
        if(save(admin)){
            return Result.ok().setMsg("添加成功").setData(admin);
        }
        return Result.fail().setMsg("添加失败").setCode(1);
    }
}
